﻿using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using Microsoft.JSInterop;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;

namespace ToPDF.Pages
{
    public partial class HandlePage
    {


        public string PrintPDF = "";
        public bool _PDF = false, Bo = true;
        private const string WkhtmltopdfProcessName = "wkhtmltopdf";
        private Loading loadingModal = new();
        private bool IsLoading { get; set; }
        public string? PrintUrl { get; private set; }
        private void KillAllWkhtmltopdfProcesses()
        {
            var pro = Process.GetProcessesByName(WkhtmltopdfProcessName);
            foreach (var item in pro)
            {
                try
                {
                    item.Kill();
                }
                catch (Exception)
                {

                    throw;
                }
            }
        }



        private void TogglePDF()
        {
            if (Bo)
            {
                Bo = false;
            }
            else
            {
                Bo = true;
            }
        }
        private void ConvertUrlToPDF(string url)
        {
            try
            {

                var cmdParam = $"--footer-right [page]/[topage] -O Landscape {url} -";
                var webRootPath = _hostEnvironment.WebRootPath;

                var startInfo = new ProcessStartInfo
                {
                    FileName = Path.Combine(webRootPath, PDF.WkhtmltopdfExePath),
                    Arguments = cmdParam,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                using var process = new Process { StartInfo = startInfo };
                process.Start();

                using (var memoryStream = new MemoryStream())
                {
                    process.StandardOutput.BaseStream.CopyTo(memoryStream);
                    memoryStream.Position = 0;


                    var base64String = Convert.ToBase64String(memoryStream.ToArray());

                    PrintPDF = $"data:{PDF.PdfContentType};base64,{base64String}";
                    _PDF = true;

                }

                process.WaitForExit();

            }
            catch (Exception)
            {

            }
            finally
            {

            }
        }

     

        private async Task GoToLocal(string type)
        {
            KillAllWkhtmltopdfProcesses();
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            IsLoading = true;
            switch (type)
            {
                case "1":
                    await Task.Run(() =>
                    {

                        ConvertUrlToPDF(PrintUrl);

                    });
                    break;
                case "2":
                    string result = await JSRuntime.InvokeAsync<string>("convertToPdf", PrintUrl);

                    result = result?.ToUpper();
                    if ("OK".Equals(result))
                    {

                        string pdfOutputPath = Path.Combine(_hostEnvironment.ContentRootPath, "temp.pdf");

                        // 异步读取文件
                        byte[] pdfBytes = await File.ReadAllBytesAsync(pdfOutputPath);

                        // 直接从字节数组转换为Base64，无需显式使用MemoryStream
                        string base64String = Convert.ToBase64String(pdfBytes);

                        // 更新PDF显示状态
                        PrintPDF = $"data:{PDF.PdfContentType};base64,{base64String}";
                        _PDF = true;
                    }
                    break;
            }

            stopwatch.Stop();
            loadingModal.SS = (int)stopwatch.Elapsed.TotalSeconds;

            IsLoading = false;


        }
        #region ==============下载PDF==============
        private async Task DownloadPDF()
        {
            if (string.IsNullOrEmpty(PrintUrl) || string.IsNullOrEmpty(PrintPDF))
            {
                return;
            }

            string fileName = DetermineFileName();

            if (!string.IsNullOrEmpty(fileName))
            {
                try
                {
                    // 使用 using 语句确保 FileStream 在操作完成后被正确关闭和释放
                    using FileStream fileStream = new FileStream("./wwwroot/fileNames.json", FileMode.Open, FileAccess.Read);
                    var fileNameDictionary = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(fileStream);
                    fileName = fileNameDictionary != null ? ResolveFileNameFromDictionary(fileNameDictionary, PrintUrl, fileName) : fileName;
                }
                catch (Exception ex)
                {
                    HandleFileReadError(ex);
                    return;
                }

                await JSRuntime.InvokeVoidAsync("downloadFileFromBase64", fileName, PrintPDF);
            }
        }

        private string DetermineFileName()
        {
            // 基于PrintUrl简单判断，或提供默认值
            // 这里可以根据实际需求逻辑进一步细化
            return "example.pdf";
        }

        private string ResolveFileNameFromDictionary(Dictionary<string, string> fileNameDictionary, string printUrl, string currentFileName)
        {
            foreach (var kvp in fileNameDictionary)
            {
                if (printUrl.Contains(kvp.Key))
                {
                    return printUrl.Contains("-1") || printUrl.Contains("YX")
                        ? $"运行 {kvp.Value}.pdf"
                        : $"检修 {kvp.Value}.pdf";
                }
            }
            return currentFileName; // 如果没有匹配项，返回原始文件名
        }

        private void HandleFileReadError(Exception ex)
        {
            Console.Error.WriteLine($"Error reading fileNames.json: {ex.Message}");
            // 可以根据需要添加其他错误处理逻辑，如日志记录或通知用户
        }
        #endregion

    }
}
